home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Source Code / C / Snippets / MPS disk v1.0.1 / Chapter 03 / Standard Stuff.c < prev    next >
Encoding:
Text File  |  1992-05-19  |  18.9 KB  |  500 lines  |  [TEXT/KAHL]

  1.                 Quit from the File menu. Our main event
  2.                                     loop exists when gQuit is TRUE. */
  3.  
  4. Boolean        gInBackground;        /*    gInBackground is maintained by our osEvent
  5.                                     handling routines. Any part of the program
  6.                                     can check it to find out if it is currently
  7.                                     in the background. */
  8.  
  9.  
  10. /*******************************************************************************
  11.  
  12.     Define HiWrd and LoWrd macros for efficiency.
  13.  
  14. *******************************************************************************/
  15.  
  16. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  17. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  18.  
  19.  
  20. /*******************************************************************************
  21.  
  22.     main
  23.  
  24.     Entry point for our program. We initialize the toolbox, make sure we are
  25.     running on a sufficiently studly machine, and put up the menubar. Finally,
  26.     we start polling for events and handling them by entering our main event
  27.     loop.
  28.  
  29. *******************************************************************************/
  30. main()
  31. {
  32.     /*    If you have stack requirements that differ from the default,
  33.         then you could use SetApplLimit to increase StackSpace at
  34.         this point, before calling MaxApplZone. */
  35.  
  36.     MaxApplZone();                    /* Expand the heap so code segments load
  37.                                        at the top */
  38.     InitToolbox();                    /* Initialize the program */
  39.     MainEventLoop();                /* Call the main event loop */
  40. }
  41.  
  42.  
  43. /*******************************************************************************
  44.  
  45.     InitToolbox
  46.  
  47.     Set up the whole world, including global variables, Toolbox managers, and
  48.     menus.
  49.  
  50. *******************************************************************************/
  51. void InitToolbox()
  52. {
  53.     Handle        menuBar;
  54.     EventRecord event;
  55.     short        count;
  56.  
  57.     gInBackground = FALSE;
  58.     gQuit = FALSE;
  59.  
  60.     InitGraf((Ptr) &qd.thePort);
  61.     InitFonts();
  62.     InitWindows();
  63.     InitMenus();
  64.     TEInit();
  65.     InitDialogs(NIL);
  66.     InitCursor();
  67.  
  68.     /*    This next bit of code waits until MultiFinder brings our application
  69.         to the front. This gives us a better effect if we open a window at
  70.         startup. */
  71.  
  72.     for (count = 1; count <= 3; ++count)
  73.         EventAvail(everyEvent, &event);
  74.  
  75.     SysEnvirons(curSysEnvVers, &gMac);
  76.  
  77.     if (gMac.machineType < 0)
  78.         DeathAlert(errWimpyROMs);
  79.  
  80.     if (gMac.systemVersion < 0x0600)
  81.         DeathAlert(errWimpySystem);
  82.  
  83.     if (!TrapExists(_WaitNextEvent))
  84.         DeathAlert(errWeirdSystem);
  85.  
  86.     menuBar = GetNewMBar(rMenuBar);            /* Read menus into menu bar */
  87.     if ( menuBar == NIL )
  88.          DeathAlert(errNoMenuBar);
  89.     SetMenuBar(menuBar);                    /* Install menus */
  90.     DisposHandle(menuBar);
  91.     AddResMenu(GetMHandle(mApple), 'DRVR');    /* Add DA names to Apple menu */
  92.     AdjustMenus();
  93.     DrawMenuBar();
  94. }
  95.  
  96.  
  97. /*******************************************************************************
  98.  
  99.     MainEventLoop
  100.  
  101.     Get events forever, and handle them by calling HandleEvent. First, call
  102.     DoAdjustCursor to set our cursor shape, and to set the cursor region. We
  103.     then call WaitNextEvent() to get the event. This is OK, because we know
  104.     we’re running on System 6.0 or later by this time. If we got an event, we
  105.     handle it by calling HandleEvent(). But before doing that, we call
  106.     DoAdjustCursor again in case our application had fallen asleep under
  107.     MultiFinder.
  108.  
  109. *******************************************************************************/
  110. void MainEventLoop()
  111. {
  112.     RgnHandle    cursorRgn;
  113.     Boolean        gotEvent;
  114.     EventRecord    event;
  115.     Point        mouse;
  116.  
  117.     cursorRgn = NIL;
  118.     while ( !gQuit ) {
  119.         gotEvent = WaitNextEvent(everyEvent, &event, MAXLONG, cursorRgn);
  120.         if ( gotEvent ) {
  121.             HandleEvent(&event);
  122.         }
  123.     }
  124. }
  125.  
  126.  
  127. /*******************************************************************************
  128.  
  129.     HandleEvent
  130.  
  131.     Do the right thing for an event. Determine what kind of event it is, and
  132.     call the appropriate routines.
  133.  
  134. *******************************************************************************/
  135. void HandleEvent(EventRecord *event)
  136. {
  137.     switch ( event->what ) {
  138.         case mouseDown:
  139.             HandleMouseDown(event);
  140.             break;
  141.         case keyDown:
  142.         case autoKey:
  143.             HandleKeyPress(event);
  144.             break;
  145.         case activateEvt:
  146.             HandleActivate(event);
  147.             break;
  148.         case updateEvt:
  149.             HandleUpdate(event);
  150.             break;
  151.         case diskEvt:
  152.             HandleDiskInsert(event);
  153.             break;
  154.         case osEvt:
  155.             HandleOSEvent(event);
  156.             break;
  157.     }
  158. }
  159.  
  160.  
  161. /*******************************************************************************
  162.  
  163.     HandleActivate
  164.  
  165.     This is called when a window is activated or deactivated. In this sample,
  166.     the Window Manager’s handling of activate and deactivate events is
  167.     sufficient. Other applications may have TextEdit records, controls, lists,
  168.     etc., to activate/deactivate.
  169.  
  170. *******************************************************************************/
  171. void HandleActivate(EventRecord *event)
  172. {
  173.     WindowPtr    theWindow;
  174.     Boolean        becomingActive;
  175.  
  176.     theWindow = (WindowPtr) event->message;
  177.     becomingActive = (event->modifiers & activeFlag) != 0;
  178.     if ( IsAppWindow(theWindow) ) {
  179.         DrawGrowIcon(theWindow);
  180.         /* DoActivateWindow(theWindow, becomingActive) */;
  181.     }
  182. }
  183.  
  184.  
  185. /*******************************************************************************
  186.  
  187.     HandleDiskInsert
  188.  
  189.     Called when we get a disk inserted event. Check the upper word of the
  190.     event message; if it’s non-zero, then a bad disk was inserted, and it
  191.     needs to be formatted.
  192.  
  193. *******************************************************************************/
  194. void HandleDiskInsert(EventRecord *event)
  195. {
  196.     Point    aPoint = {100, 100};
  197.  
  198.     if ( HiWrd(event->message) != noErr ) {
  199.         (void) DIBadMount(aPoint, event->message);
  200.     }
  201. }
  202.  
  203.  
  204. /*******************************************************************************
  205.  
  206.     HandleKeyPress
  207.  
  208.     The user pressed a key. What are you going to do about it?
  209.  
  210. *******************************************************************************/
  211. void HandleKeyPress(EventRecord *event)
  212. {
  213.     char    key;
  214.  
  215.     key = event->message & charCodeMask;
  216.     if ( event->modifiers & cmdKey ) {        /* Command key down? */
  217.         AdjustMenus();                        /* Enable/disable/check menu items properly */
  218.         HandleMenuCommand(MenuKey(key));
  219.     } else {
  220.         /* DoKeyPress(event) */;
  221.     }
  222. }
  223.  
  224.  
  225. /*******************************************************************************
  226.  
  227.     HandleMouseDown
  228.  
  229.     Called to handle mouse clicks. The user could have clicked anywhere, so
  230.     let’s first find out where by calling FindWindow. That returns a number
  231.     indicating where in the screen the mouse was clicked. “switch” on that
  232.     number and call the appropriate routine.
  233.  
  234. *******************************************************************************/
  235. void HandleMouseDown(EventRecord *event)
  236. {
  237.     long        newSize;
  238.     Rect        growRect;
  239.     WindowPtr    theWindow;
  240.     short        part = FindWindow(event->where, &theWindow);
  241.  
  242.     switch ( part ) {
  243.         case inMenuBar:                /* Process a mouse menu command (if any) */
  244.             AdjustMenus();
  245.             HandleMenuCommand(MenuSelect(event->where));
  246.             break;
  247.         case inSysWindow:            /* Let the system handle the mouseDown */
  248.             SystemClick(event, theWindow);
  249.             break;
  250.         case inContent:
  251.             if ( theWindow != FrontWindow() )
  252.                 SelectWindow(theWindow);
  253.             else
  254.                 /* DoContentClick(event, theWindow) */;
  255.             break;
  256.         case inDrag:                /* Pass screenBits.bounds to get all gDevices */
  257.             DragWindow(theWindow, event->where, &qd.screenBits.bounds);
  258.             break;
  259.         case inGrow:
  260.             growRect = qd.screenBits.bounds;
  261.             growRect.top = growRect.left = 80;        /* Arbitrary minimum size. */
  262.             newSize = GrowWindow(theWindow, event->where, &growRect);
  263.             if (newSize != 0) {
  264.                 InvalidateScrollbars(theWindow);
  265.                 SizeWindow(theWindow, LoWrd(newSize), HiWrd(newSize), TRUE);
  266.                 InvalidateScrollbars(theWindow);
  267.             }
  268.             break;
  269.         case inGoAway:
  270.             if (TrackGoAway(theWindow, event->where))  {
  271.                 CloseAnyWindow(theWindow);
  272.             }
  273.             break;
  274.         case inZoomIn:
  275.         case inZoomOut:
  276.             if (TrackBox(theWindow, event->where, part)) {
  277.                 SetPort(theWindow);
  278.                 EraseRect(&theWindow->portRect);
  279.                 ZoomWindow(theWindow, part, TRUE);
  280.                 InvalRect(&theWindow->portRect);
  281.             }
  282.             break;
  283.     }
  284. }
  285.  
  286.  
  287. /*******************************************************************************
  288.  
  289.     HandleOSEvent
  290.  
  291.     Deal with OSEvents (formerly, app4Events). These are message that
  292.     MultiFinder -- known as the Process Manager under System 7.0 -- sends to
  293.     us. Here, we deal with suspend and resume message.
  294.  
  295. *******************************************************************************/
  296. void HandleOSEvent(EventRecord *event)
  297. {
  298.     switch ((event->message >> 24) & 0x00FF) {        /* High byte of message */
  299.         case suspendResumeMessage:
  300.  
  301.             /*    In our SIZE resource, we say that we are MultiFinder aware.
  302.                 This means that we take on the responsibility of activating
  303.                 and deactivating our own windows on suspend/resume events. */
  304.  
  305.             gInBackground = (event->message & resumeFlag) == 0;
  306.             if (FrontWindow()) {
  307.                 DrawGrowIcon(FrontWindow());
  308.                 /* DoActivateWindow(FrontWindow(), !gInBackground); */
  309.             }
  310.             break;
  311.         case mouseMovedMessage:
  312.             break;
  313.     }
  314. }
  315.  
  316.  
  317. /*******************************************************************************
  318.  
  319.     HandleUpdate
  320.  
  321.     This is called when an update event is received for a window. It calls
  322.     DoUpdateWindow to draw the contents of an application window. As an
  323.     efficiency measure that does not have to be followed, it calls the drawing
  324.     routine only if the visRgn is non-empty. This will handle situations where
  325.     calculations for drawing or drawing itself is very time-consuming.
  326.  
  327. *******************************************************************************/
  328. void HandleUpdate(EventRecord *event)
  329. {
  330.     WindowPtr    theWindow = (WindowPtr) event->message;
  331.     if ( IsAppWindow(theWindow) ) {
  332.         BeginUpdate(theWindow);                /* This sets up the visRgn */
  333.         if (!EmptyRgn(theWindow->visRgn)) {    /* Draw if updating needs to be done */
  334.             SetPort(theWindow);
  335.             EraseRgn(theWindow->visRgn);
  336.             /* DoUpdateWindow(event) */;
  337.             DrawGrowIcon(theWindow);
  338.         }
  339.         EndUpdate(theWindow);
  340.     }
  341. }
  342.  
  343.  
  344. /*******************************************************************************
  345.  
  346.     AdjustMenus
  347.  
  348.     Enable and disable menus based on the current state. The user can only
  349.     select enabled menu items. We set up all the menu items before calling
  350.     MenuSelect or MenuKey, since these are the only times that a menu item can
  351.     be selected. Note that MenuSelect is also the only time the user will see
  352.     menu items. This approach to deciding what enable/disable state a menu
  353.     item has the advantage of concentrating all the decision-making in one
  354.     routine, as opposed to being spread throughout the application. Other
  355.     application designs may take a different approach that is just as valid.
  356.  
  357. *******************************************************************************/
  358. void AdjustMenus()
  359. {
  360.     WindowPtr    window;
  361.     MenuHandle    menu;
  362.  
  363.     window = FrontWindow();
  364.  
  365.     menu = GetMHandle(mFile);
  366.     if ( window != NIL )
  367.         EnableItem(menu, iClose);
  368.     else
  369.         DisableItem(menu, iClose);
  370.  
  371.     menu = GetMHandle(mEdit);
  372.     if ( IsDAWindow(window) ) {        /* A desk accessory might need the edit menu… */
  373.         EnableItem(menu, iUndo);
  374.         EnableItem(menu, iCut);
  375.         EnableItem(menu, iCopy);
  376.         EnableItem(menu, iClear);
  377.         EnableItem(menu, iPaste);
  378.     } else {                        /* … but we don’t use it. */
  379.         DisableItem(menu, iUndo);
  380.         DisableItem(menu, iCut);
  381.         DisableItem(menu, iCopy);
  382.         DisableItem(menu, iClear);
  383.         DisableItem(menu, iPaste);
  384.     }
  385. }
  386.  
  387.  
  388. /*******************************************************************************
  389.  
  390.     HandleMenuCommand
  391.  
  392.     This is called when an item is chosen from the menu bar (after calling
  393.     MenuSelect or MenuKey). It performs the right operation for each command.
  394.     It is good to have both the result of MenuSelect and MenuKey go to one
  395.     routine like this to keep everything organized.
  396.  
  397. *******************************************************************************/
  398. void HandleMenuCommand(menuResult)
  399.     long        menuResult;
  400. {
  401.     short        menuID;                /* The resource ID of the selected menu */
  402.     short        menuItem;            /* The item number of the selected menu */
  403.     Str255        daName;
  404.  
  405.     menuID = HiWrd(menuResult);
  406.     menuItem = LoWrd(menuResult);
  407.     switch ( menuID ) {
  408.         case mApple:
  409.             switch ( menuItem ) {
  410.                 case iAbout:
  411.                     (void) Alert(rAboutAlert, NIL);
  412.                     break;
  413.                 default:            /* All non-About items in this menu are DAs */
  414.                     GetItem(GetMHandle(mApple), menuItem, daName);
  415.                     (void) OpenDeskAcc(daName);
  416.                     break;
  417.             }
  418.             break;
  419.         case mFile:
  420.             switch ( menuItem ) {
  421.                 case iNew:
  422.                     /* DoNewWindow(); */
  423.                     break;
  424.                 case iClose:
  425.                     CloseAnyWindow(FrlRect(&tempRect);
  426.     EraseRect(&tempRect);
  427.  
  428.     tempRect = theWindow->portRect;
  429.     tempRect.top = tempRect.bottom - 15;
  430.     InvalRect(&tempRect);
  431.     EraseRect(&tempRect);
  432. }
  433.  
  434.  
  435. /*******************************************************************************
  436.  
  437.     TrapExists
  438.  
  439.     Check to see if a given trap is implemented. The recommended approach to
  440.     see if a trap is implemented is to see if the address of the trap routine
  441.     is the same as the address of the _Unimplemented trap. However, we must
  442.     also make sure that the trap is contained in the trap table on the machine
  443.     we’re running on. Not all Macintoshes have the same sized trap tables. We
  444.     call NumToolboxTraps to find out the size of the table. If the trap we are
  445.     examining falls off the end, then we treat it as automatically being
  446.     unimplemented.
  447.  
  448. *******************************************************************************/
  449. Boolean    TrapExists(short theTrap)
  450. {
  451.     TrapType    theTrapType;
  452.  
  453.     theTrapType = GetTrapType(theTrap);
  454.     if ((theTrapType == ToolTrap) && ((theTrap &= 0x07FF) >= NumToolboxTraps()))
  455.         return false;
  456.     else
  457.         return (NGetTrapAddress(_Unimplemented, ToolTrap) !=
  458.                 NGetTrapAddress(theTrap, theTrapType));
  459. }
  460.  
  461.  
  462. /*******************************************************************************
  463.  
  464.     GetTrapType
  465.  
  466.     Check the bits of a trap number to determine its type. If bit 11 is set,
  467.     it’s a toolbox trap. Otherwise, it’s an OS trap.
  468.  
  469. *******************************************************************************/
  470. TrapType    GetTrapType(short theTrap)
  471. {
  472.     if ((theTrap & 0x0800) == 0)                    /* Per D.A. */
  473.         return (OSTrap);
  474.     else
  475.         return (ToolTrap);
  476. }
  477.  
  478.  
  479. /*******************************************************************************
  480.  
  481.     NumToolboxTraps
  482.  
  483.     Find the size of the Toolbox trap table. This can be either 0x0200 or
  484.     0x0400 bytes, depending on which Macintosh we are running on. We determine
  485.     the size by taking advantage of an anomaly of the smaller trap table: any
  486.     entries that fall beyond the end of the table are mirrored back down into
  487.     the lower part. For example, on a large table, trap numbers A86E and AA6E
  488.     correspond to different routines. However, on a small table, they
  489.     correspond to the same routine. By checking the addresses of these
  490.     routines, we can determine the size of the table.
  491.  
  492. *******************************************************************************/
  493. short    NumToolboxTraps(void)
  494. {
  495.     if (NGetTrapAddress(0xA86E, ToolTrap) == NGetTrapAddress(0xAA6E, ToolTrap))
  496.         return (0x200);
  497.     else
  498.         return (0x400);
  499. }
  500.